package edu.chen.controller;

import edu.chen.dto.execution.BasicExecution;
import edu.chen.dto.Result;
import edu.chen.entity.Student;
import edu.chen.entity.User;
import edu.chen.exception.LibraryException;
import edu.chen.exception.login.LoginException;
import edu.chen.exception.login.NoUserException;
import edu.chen.service.LeaseService;
import edu.chen.service.UserService;
import edu.chen.util.CookieUtils;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
@RequestMapping("/user")
public class UserController {
    private Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private LeaseService leaseService;

    UserController(){
        BasicConfigurator.configure();
        logger.setLevel(Level.DEBUG);
    }

    /**
     * 跳转方法
     * @return
     */
    @RequestMapping(value = "/loginView")
    private String loginView(){
        return "login";
    }

    /**
     * 登录信息处理方法
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    private Result login(@RequestParam String username, @RequestParam String password
            , HttpServletRequest request, HttpServletResponse response){
        logger.debug("username:"+username+" and password:"+password);
        BasicExecution basicExecution;
        try {
            User user = userService.verifyLogin(username, password);     //调用方法获得结果
            /**
             * 保存登录状态有两步
             * 1.将user保存到本次回话的session
             * 2.将user在本地村委cookie
             */
            request.getSession().setAttribute("loginUser", user);    //获取data属性(User),并注入session属性

            String data = username+"#"+password;

            new CookieUtils().saveCookie(response,"autoLogin",data);

            return new Result();
        }catch (NoUserException e){
            return new Result("用户名错误");
        }catch (LoginException e){
            return new Result("登陆错误");
        }
//
//        return new Result<BasicExecution>(false, basicExecution);

        /**
         * 在直接返回Result对象时,因为result的T为User,User中的student属性为懒加载,所以在页面中会出现报错
         * 1.可以在MappingJackson2HttpMessageConverter中设置自己定义的Mapper,
         *          改变其中的SerializationFeature.FAIL_ON_EMPTY_BEANS属性为false
         *  public class CustomMapper extends ObjectMapper{
         *        public CustomMapper() {
         *           this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
         *           // 设置 SerializationFeature.FAIL_ON_EMPTY_BEANS 为 false
         *           this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
         *       }
         *    }
         * 2.因为此处的student甚至user,都不是必须的 所以在传递信息之前可以直接设置为null
         */
//        return userService.verifyLogin(username,password);
    }

    /**
     * 用户退出处理方法
     */
    @RequestMapping(value = "/exit",method = RequestMethod.GET)
    private String exit(HttpServletRequest request,HttpServletResponse response){
        //操作时 不仅删除session里面的loginUser属性 而且需要删除cookie
        new CookieUtils().removeCookie(response,"autoLogin");
        request.getSession().removeAttribute("loginUser");
//        throw new NoUserException("异常测试");
        return "redirect:/";
    }



    /**
     * 跳转方法
     * @param modelAndView 携带标志位跳转
     * @param sign  标志位
     * @return
     */
    @RequestMapping(value = "/userInfo")
    private ModelAndView userInfo(ModelAndView modelAndView,@RequestParam("sign") int sign /*,@RequestParam String username*/) {
        /**
         * 因为在验证登陆的时候已经将user信息存入Session
         * 所以此处可以直接在session中获得该属性
         */
        modelAndView.setViewName("userInfo");
        /**
         * 因为在归还书本操作的时候同样是该页面,但是显示bookData
         * 所以此处携带标记(sign),跳转
         * sign=1  ==>  iframe为userdata
         * sign=2  ==>  iframe为bookData
         */
        modelAndView.getModel().put("sign",sign);
        return modelAndView;
    }

    /**
     * 用户信息更新处理方法
     * @param user
     * @param student
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateUserInfo",method = RequestMethod.POST)
    @ResponseBody
//    @RequestParam("student_id") int student_id,@RequestParam("user_age") int user_age,@RequestParam("user_sex") int user_sex
    /**
     *  1.因为user的信息可以会很多所以直接使用user对象来接收,
     *          user中的student对象不能直接注入,所以用一个student对象接收student_id之后再注入
     *  2.因为使用@RequestParam指定的参数必须存在,且类型相同 所以此处不使用该注解绑定参数
     */
    private String updateUserInfo(User user,Student student,HttpServletRequest request){
        try {
            logger.debug(user);
            user.setStudent(student);
            userService.updateUserInfo(user);       //更新用户信息
            User user1 = userService.getUserInfo(user.getUsername());       //重新获取User信息
            request.getSession().setAttribute("loginUser",user1);       //重新注入Session属性
            return "success";
        }catch (Exception e){
            return "error";
        }
    }

    /**
     * 简单跳转方法
     * @return
     */
    @RequestMapping(value = "userData")
    private String userData(){
        return "userData";
    }

    /**
     * 简单跳转方法
     * @return
     */
    @RequestMapping(value = "modifyPassword")
    private String modifyPassword(){
        return "modifyPassword";
    }


    @RequestMapping(value = "test")
    private String test() throws  LibraryException{
        throw new LibraryException("出错了!!");
    }
}
